package com.arron.jvm.ref;

import java.lang.ref.SoftReference;

/**
 * @Classname SoftRefDemo
 * @Date 2020/8/23 23:33
 * @Created by 刘
 */
public class SoftRefDemo {

    /**
     * 软引用在内存充足的不会被回收，在内存不足的时候会被回收
     * @param args
     */
    public static void main(String[] args) {

//        momory_enough();
        momory_no_enough();
    }

    private static void momory_enough() {
        Object o1 = new Object();
        //软引用
        SoftReference<Object> o2 = new SoftReference<Object>(o1);
        System.out.println(o1);
        System.out.println(o2.get());

        o1=null;
        System.gc();

        System.out.println(o1);
        System.out.println(o2.get());
    }


    private static void momory_no_enough() {

        Object o1 = new Object();
        //软引用
        SoftReference<Object> o2 = new SoftReference<Object>(o1);
        System.out.println(o1);
        System.out.println(o2.get());

        o1=null;
        System.gc();

        try {
            Byte[] bytes = new Byte[30 * 1024 * 1024];
        }catch (Throwable e){
            e.printStackTrace();
        }finally {
            //null
            //null
            System.out.println(o1);
            System.out.println(o2.get());
        }


    }

}
